/*******************************************************************************
 * Copyright (c) 2011 Grupo de Sistemas Inteligentes (GSI) - DIT UPM
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/
package es.upm.dit.gsi.eclipse.jadex.adfmanager.wizards;


import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.*;
import org.eclipse.jface.operation.*;

import java.io.File;
import java.lang.reflect.InvocationTargetException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.ui.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import es.upm.dit.gsi.eclipse.jadex.util.ImageFactory;

/**
 * Wizard for adding a new Configuration to the selected agent
 * 
 * It has got 3 pages (por decidir)
 *  - Page1: 
 *  - Page2: 
 *  - Page3: 
 *  
 * @author Mario Moreno
 */

public class AddConfigurationWizard extends Wizard implements INewWizard {
	private AddConfigurationWizardPage1 page1;
	private ISelection selection;

	/**
	 * Constructor for AddConfigurationWizard
	 */
	public AddConfigurationWizard(ISelection selection) {
		super();
		setNeedsProgressMonitor(true);
		this.selection = selection;
		setDefaultPageImageDescriptor(ImageFactory.getImageDescriptor(ImageFactory.GSI_BANNER_SMALL));
	}
	
	/**
	 * Adding pages to the wizard.
	 */
	public void addPages() {
		page1 = new AddConfigurationWizardPage1(selection);
		addPage(page1);
	}

	/**
	 * This method is called when 'Finish' button is pressed in
	 * the wizard. We will create an operation and run it
	 * using wizard as execution context.
	 */
	public boolean performFinish() {
		final IFile agentFile = (IFile)((IStructuredSelection)selection).getFirstElement();
		//Configuration preferences
		final String debugging = page1.getDebugging();
	
		
		//Configuration addition
		IRunnableWithProgress op = new IRunnableWithProgress() {
			public void run(IProgressMonitor monitor) throws InvocationTargetException {
				try {
					doFinish(agentFile, debugging, monitor);
				} catch (CoreException e) {
					throw new InvocationTargetException(e);
				} finally {
					monitor.done();
				}
			}
		};
		
		try {
			getContainer().run(true, false, op);
		} catch (InterruptedException e) {
			return false;
		} catch (InvocationTargetException e) {
			Throwable realException = e.getTargetException();
			MessageDialog.openError(getShell(), "Error", realException.getMessage());
			return false;
		}
		return true;
	}
	
	/**
	 * The worker method. It will add the necessary information to the ADF file in 
	 * order to configure the new Configuration.
	 */
	private void doFinish(
			IFile agentFile,
			String debugging,
			IProgressMonitor monitor)
		throws CoreException {
		
		monitor.beginTask("Modificating ADF File", 2);
		
		if(debugging != null){
		
		try{
		DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
		Document doc = docBuilder.parse(agentFile.getRawLocation().toOSString());
	 
		//Get the configuration element 
		Node configurations = doc.getElementsByTagName("configurations").item(0);

		Element newConfiguration = doc.createElement("configuration");
		newConfiguration.setAttribute("name", "default");
		
	
		
		
		configurations.appendChild(newConfiguration);
	 
		//write the content into xml file
	    TransformerFactory transformerFactory = TransformerFactory.newInstance();
	    transformerFactory.setAttribute("indent-number", new Integer(4));
	    Transformer transformer;
		transformer = transformerFactory.newTransformer();
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
	    DOMSource source = new DOMSource(doc);
	    StreamResult result =  new StreamResult(new File(agentFile.getRawLocation().toOSString()));
	    transformer.transform(source, result);
	    agentFile.refreshLocal(IFile.DEPTH_INFINITE, monitor);
		}
		catch(Exception e1){
			e1.printStackTrace();
		}
	    System.out.println("Done");
	    
		}
		
		monitor.worked(1);
	}
	
	
	/*
	private void throwCoreException(String message) throws CoreException {
		IStatus status =
			new Status(IStatus.ERROR, "Agent_Editor", IStatus.OK, message, null);
		throw new CoreException(status);
	}
	*/

	/**
	 * We will accept the selection in the workbench to see if
	 * we can initialize from it.
	 * @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection)
	 */
	public void init(IWorkbench workbench, IStructuredSelection selection) {
		this.selection = selection;
	}
}